﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace GSMMODEM
{

    public class SendSMS : ISendSms
    {

        #region 变量

        private GsmModem sms;

        #endregion

        #region 构造函数
        public SendSMS()
        {
            sms = GsmModem.GetInstance("COM3", 9600);
            sms.Init();
        }
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="comPort">COM端口名</param>
        /// <param name="baudRate">波特率</param>
        public SendSMS(string comPort, int baudRate)
        {
            sms = GsmModem.GetInstance(comPort, baudRate);//创建实例
            sms.Init();                                      //初始化端口
        }

        #endregion

        #region 发送消息
        /// <summary>
        /// 发送短消息
        /// </summary>
        /// <param name="phone">终端号码</param>
        /// <param name="msg">消息</param>
        /// <returns>返回是否成功</returns>
        public bool SendSms(string phone, string msg)
        {
            bool retVal = sms.SendMsg(phone,msg);
            return retVal;
        }

        #endregion
    }

    public class ReceiveSMS : AbstractReceiveSms
    {
        #region 变量

        private GsmModem sms;

        #endregion

        #region 构造函数
        public ReceiveSMS()
        {
            sms = GsmModem.GetInstance("COM3", 9600);//创建实例
            sms.Init();                                 //初始化端口
            
        }
         public ReceiveSMS(string comPort, int baudRate)
        {
            sms = GsmModem.GetInstance(comPort, baudRate);//创建实例
            sms.Init();                                      //初始化端口
        }
        #endregion

        #region 事件,订阅
        void sms_OnRecieved(object sender, SmsInfo sms)
        {
            EventNewSms(sms);   //传递消息
        }

        public override event Action<SmsInfo> EventNewSms;
        #endregion

        #region 公开方法
        /// <summary>
        /// 接收消息
        /// 由 OnRecieved 事件取回
        /// </summary>
        public override void StartReceiveSms()
        {
            IList<SmsInfo> item = sms.GetUnreadMsg();
            foreach (SmsInfo smsinfo in item)
            {
                EventNewSms(smsinfo);   //传递消息
            }
            sms.OnRecieved += new GsmModem.OnRecievedHandler(sms_OnRecieved);//订阅消息
        }
        /// <summary>
        /// 释放对象
        /// </summary>
        public override void Dispose()
        {
            if(sms.IsOpen)
            {
                this.sms.Close();
            }else
            {
                this.sms.Init();
                this.Dispose();
                return;
            }
        }
        #endregion

        #region 析构函数
       ~ReceiveSMS()
        {
            this.Dispose();
        }

       #endregion
    }
}
